<template>
  <div class="upload">
    <van-uploader
      :modelValue="modelValue"
      :max-count="limit"
      :before-delete="onDelete"
      :after-read="onUpload"
      :show-upload="showUpload"
      :deletable="deletable"
    >
<!--      <template #preview-delete>-->
<!--        <img src="https://img.hzanchu.com/acimg/6cfcbbc91a02575685a796328d66a2a3.png" alt="" />-->
<!--      </template>-->
      <template #default>
        <img src="https://img.hzanchu.com/acimg/dc20b241611d1f17a6d37457bc0d05c7.png" alt="" />
      </template>
    </van-uploader>
  </div>
</template>

<script setup>
import { ref, watch, reactive, defineProps, defineEmits } from 'vue'
import { Toast } from 'vant'
import { imgUpload } from '@/service/village'
import Compressor from 'compressorjs'

const props = defineProps({
  limit: {
    type: Number,
    default: 10
  },
  showUpload: { // 是否展示上传区域
    type: Boolean,
    default: true
  },
  deletable: { // 是否展示删除按钮
    type: Boolean,
    default: true
  },
  modelValue: {
    type: Array,
    default: () => [],
	}
})

const emits = defineEmits(['update:modelValue'])

// 选择文件 后续处理
const onUpload = (file) => {
	new Compressor(file.file, {
		quality: 0.7,
		success(result) {
			blob2File(result).then(image => {
				uploadImage(image)
			})
		},
		error() {
			uploadImage(file.file)
		}
	})
}

const blob2File = async (blob) => {
	return new window.File([blob], blob.name, { type: blob.type })
}

const uploadImage = async (file) => {
	try {
		const form = new FormData()
		form.append('File', file)
		const result = await imgUpload(form)
		if (result) {
			emits('update:modelValue', [
				...props.modelValue,
				{
					url: result,
					status: 'done',
					isImage: true
				}
			])
		}
	} catch (err) {
		Toast('上传失败，请稍后重试。')
	}
}

const onDelete = (e) => {
	const newArr = [...props.modelValue]?.filter(item => item !== e)
	emits('update:modelValue', newArr)
}

</script>

<style scoped lang="less">
.upload {
  width: 100%;
  .btns {
    display: flex;
  }
}
.vue--picture-cropper__wrap {
  height: calc(100% - 80px - 30px);
}
.cropper-btns {
  height: 80px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 30px;
  div {
    background: #fff;
    width: 120px;
    height: 56px;
    line-height: 56px;
    text-align: center;
    font-size: 28px;
    border: 2px solid var(--van-primary-color);
    border-radius: 28px;
    margin-right: 32px;
    &:nth-of-type(1) {
      color: var(--van-primary-color);
    }
    &:nth-of-type(2) {
      color: #fff;
      background: var(--van-primary-color);
    }
  }
}
</style>
